<template>
  <el-card class="box-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <el-button type="primary" :icon="Plus" @click="addOrEditOneTrademark()"
          >添加品牌</el-button
        >
        <el-dialog
          v-model="dialogFormVisible"
          :title="`${formList.id > 0 ? '修改' : '添加'}品牌`"
          top="0vh"
        >
          <el-form
            :model="formList"
            class="dialog-height"
            :rules="rules"
            ref="tradeMarkRef"
          >
            <el-form-item
              label="品牌名称"
              :label-width="formLabelWidth"
              prop="tmName"
            >
              <el-input
                v-model="formList.tmName"
                autocomplete="off"
                input-style="width:614px"
              />
            </el-form-item>
            <el-form-item
              label="品牌LOGO"
              :label-width="formLabelWidth"
              prop="logoUrl"
            >
              <el-upload
                class="avatar-uploader"
                :action="`${BASE_URL}/admin/product/fileUpload`"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="formList.logoUrl"
                  :src="formList.logoUrl"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon el-upload">
                  <Plus />
                </el-icon>
                <template #tip>
                  <div class="el-upload__tip">
                    只能上传jpg/png文件，且不超过200kb
                  </div></template
                >
              </el-upload>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="submitForm"> 确 定 </el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </template>
    <el-table
      :data="tradeMarkList"
      border
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column prop="logoUrl" label="品牌LOGO">
        <template v-slot="{ row }">
          <el-image :src="row.logoUrl" lazy class="trademark-img"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template v-slot="{ row }">
          <el-button
            type="warning"
            :icon="Edit"
            size="small"
            title="修改品牌信息"
            @click="addOrEditOneTrademark(row)"
          ></el-button>
          <el-button
            type="danger"
            :icon="Delete"
            size="small"
            @click="deleteOneTrademark(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { Edit, Plus, Delete } from "@element-plus/icons-vue";
import {
  TrademarkItem,
  TrademarkList,
} from "@/api/product/modules/trademarkModules.ts";
import {
  getTrademarkListApi,
  addTradeMarkApi,
  editTradeMarkApi,
  deleteOneTrademarkApi,
} from "@/api/product/trademark";
import { onMounted, ref, reactive } from "vue";
defineOptions({
  name: "Trademark",
});
const tradeMarkList = ref<TrademarkList>([]);
const currentPage = ref(1); // 当前页
const pageSize = ref(5); // 一页几条
const total = ref(0); // 总页数
const loading = ref(false);
const getTrademarkList = async () => {
  loading.value = true;
  const result = await getTrademarkListApi(currentPage.value, pageSize.value);
  tradeMarkList.value = result.records;
  total.value = result.total;
  pageSize.value = result.size;
  loading.value = false;
};
onMounted(getTrademarkList);

const handleSizeChange = () => {
  getTrademarkList();
};
const handleCurrentChange = () => {
  getTrademarkList();
};

// 添加品牌
const dialogFormVisible = ref(false);
const formLabelWidth = "100px";

// 添加图片
import type { UploadProps } from "element-plus";
const BASE_URL = import.meta.env.VITE_API_URL;
const formList = reactive({
  id: -1,
  tmName: "",
  logoUrl: "",
});
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response
  // uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  formList.logoUrl = response.data;
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const fileTypes = ["image/jpeg", "image/png", "image/jpg"];
  if (!fileTypes.includes(rawFile.type)) {
    ElMessage.error("图片格式必须为jpg或者jpeg或者png");
    return false;
  } else if (rawFile.size > 200 * 1024) {
    ElMessage.error("图片大小不能超过200KB!");
    return false;
  }
  return true;
};

// 添加图片校验规则
const rules = reactive({
  tmName: [
    { required: true, message: "请输入品牌名称", trigger: "blur" },
    { min: 2, max: 10, message: "品牌名称长度只能为2-10位", trigger: "blur" },
  ],
  logoUrl: [{ required: true, message: "请上传品牌图片" }],
});

const tradeMarkRef = ref();
const submitForm = async () => {
  await tradeMarkRef.value.validate();
  const id = formList.id;
  if (id > 0) {
    await editTradeMarkApi(formList);
  } else {
    await addTradeMarkApi(formList.tmName, formList.logoUrl);
  }
  ElMessage.success(`${id > 0 ? "更新" : "添加"}品牌成功`);
  dialogFormVisible.value = false;
  console.log("表单校验通过"); // 可以不打印

  getTrademarkList();
  // formList.logoUrl = "";
  // formList.tmName = "";
};

// 添加或修改品牌信息
const addOrEditOneTrademark = (
  row: TrademarkItem = { tmName: "", logoUrl: "", id: -1 }
) => {
  dialogFormVisible.value = true;
  formList.tmName = row.tmName;
  formList.logoUrl = row.logoUrl;
  formList.id = row.id;
  tradeMarkRef.value?.clearValidate(); // 清空整个表单校验信息
};

// 删除一条品牌信息
const deleteOneTrademark = (row: TrademarkItem) => {
  ElMessageBox.confirm("确认要删除这条商品吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await deleteOneTrademarkApi(row.id);
      getTrademarkList();
      ElMessage({
        type: "success",
        message: "您已成功删除",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "您已取消删除",
      });
    });
};
</script>

<style scoped lang="scss">
.cancel-button {
  width: 70px;
}
.demo-pagination-block {
  margin-top: 20px;
}
.trademark-img {
  width: 150px;
  height: 80px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
.dialog-height {
  height: 287px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  // border: 1px dashed #8c939d;
}
</style>
